package com.example.ivideo_2211a.fyt

import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import com.example.common.mvi.NetworkResult
import com.example.ivideo_2211a.model.FtyTopeEntity
import kotlinx.coroutines.launch

class FYTViewModel : BaseViewModel<FYTIntent, FYTViewState, FYTResult>() {
    private val repository = FytRepository()

    override fun initialState(): FYTViewState = FYTViewState()

    override suspend fun handleIntent(intent: FYTIntent) {
        when (intent) {
            is FYTIntent.LoadTypes -> loadTypesAndVideos()
            is FYTIntent.RefreshTypes -> refreshTypesAndVideos()
            is FYTIntent.SelectType -> selectTypeAndLoadVideos(intent.type)
            is FYTIntent.LoadMoreVideos -> loadMoreVideos(intent.channelId, intent.page)
        }
    }

    private fun loadTypesAndVideos() {
        viewModelScope.launch {
            repository.getSimpleType().collect { result ->
                when (result) {
                    is NetworkResult.Loading -> {
                        updateState(currentState().copy(isLoading = true, error = null))
                    }
                    is NetworkResult.Success<List<FtyTopeEntity>> -> {
                        val types = result.data
                        val selectedType = types.firstOrNull { it.isSelected } ?: types.firstOrNull()
                        updateState(currentState().copy(
                            isLoading = false,
                            types = types,
                            currentPage = 1,
                            hasMore = types.size >= 10
                        ))
                        selectedType?.let { loadVideos(it.id, 1) }
                    }
                    is NetworkResult.Error -> {
                        updateState(currentState().copy(isLoading = false, error = result.exception.message ?: "加载失败"))
                    }
                }
            }
        }
    }

    private fun refreshTypesAndVideos() {
        viewModelScope.launch {
            repository.getSimpleType().collect { result ->
                when (result) {
                    is NetworkResult.Loading -> {
                        updateState(currentState().copy(isRefreshing = true, error = null))
                    }
                    is NetworkResult.Success<List<FtyTopeEntity>> -> {
                        val types = result.data
                        val selectedType = types.firstOrNull { it.isSelected } ?: types.firstOrNull()
                        updateState(currentState().copy(
                            isRefreshing = false,
                            types = types,
                            currentPage = 1,
                            hasMore = types.size >= 10
                        ))
                        selectedType?.let { loadVideos(it.id, 1) }
                    }
                    is NetworkResult.Error -> {
                        updateState(currentState().copy(isRefreshing = false, error = result.exception.message ?: "刷新失败"))
                    }
                }
            }
        }
    }

    private fun selectTypeAndLoadVideos(type: FtyTopeEntity) {
        updateState(currentState().copy(
            types = currentState().types.map { it.copy(isSelected = it.id == type.id) }
        ))
        loadVideos(type.id, 1)
    }

    private fun loadVideos(channelId: String, page: Int, isLoadMore: Boolean = false) {
        viewModelScope.launch {
            repository.getVideoListByChannelId(channelId, page, 10).collect { result ->
                when (result) {
                    is NetworkResult.Loading -> {
                        if (isLoadMore) {
                            updateState(currentState().copy(isLoadingMore = true, error = null))
                        } else {
                            updateState(currentState().copy(isLoading = true, error = null))
                        }
                    }
                    is NetworkResult.Success -> {
                        val newVideos = if (isLoadMore) {
                            currentState().videos + result.data
                        } else {
                            result.data
                        }
                        updateState(currentState().copy(
                            isLoading = false,
                            isLoadingMore = false,
                            videos = newVideos,
                            currentPage = page,
                            hasMore = result.data.size >= 10
                        ))
                    }
                    is NetworkResult.Error -> {
                        updateState(currentState().copy(
                            isLoading = false,
                            isLoadingMore = false,
                            error = result.exception.message ?: "加载视频失败"
                        ))
                    }
                }
            }
        }
    }

    private fun loadMoreVideos(channelId: String, page: Int) {
        if (currentState().isLoadingMore || !currentState().hasMore) return
        loadVideos(channelId, page, true)
    }
}
